<?php
class ControllerArticleArticle extends AdminController {

	public function index() {
		M('article/article', 'article_mod');
		$this->getList();
	}

	public function insert() {
		M('article/article', 'article_mod');
		if ($this->request->isPost()) {
			$this->article_mod->addArticle($this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('article/article'));
		}
		$this->getForm();
	}

	public function update() {
		M('article/article', 'article_mod');
		if ($this->request->isPost()) {
			$this->article_mod->editArticle($this->request->get['article_id'], $this->request->post);
				
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('article/article'));
		}
		$this->getForm();
	}

	public function delete() {
		M('article/article', 'article_mod');
		if ($this->request->post['selected']) {
			$this->article_mod->deleteArticle($this->request->post['selected']);
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('article/article'));
		}
		$this->getList();
	}

	protected function getList() {
		$this->document->setTitle($this->_['heading_title']);

		$this->data['categories'] = $this->article_mod->getCategories();
		
		$qf = new Query_filter();
		$total_articles = $this->article_mod->getTotalArticles($qf);
		$this->data['articles'] = $this->article_mod->getArticles($qf);
		
		foreach ($this->data['articles'] as $i => $a) {
			$this->data['articles'][$i]['link'] = U('article/index', "article_id=$a[article_id]");
		}
		
		$this->data['pagination'] = $this->pagination($total_articles)->render();
		
		$this->data['filter_category_id'] = $qf->get('filter_category_id');
		
		$this->display('article/article_list.tpl');
	}

	protected function getForm() {
		$this->document->addScript(ROOT . 'static/javascript/jquery/jquery.validate.js');
		$this->document->setTitle($this->_['heading_title']);
		$this->data['token'] = $this->session->data['token'];
		$article_id = G('article_id');
		if ($article_id) {
			$this->data['action'] = UA('article/article/update', "article_id=$article_id");
			if (!$this->request->isPost()) {
				$this->vo->data = $this->article_mod->getArticle($article_id);
			}
		}
		else {
			$this->data['action'] = UA('article/article/insert');
		}
		
		$this->data['categories'] = $this->article_mod->getCategories();
		
		$this->display('article/article_form.tpl');
	}
}